<template>
	<view class="container">
			<scroll-view class="box" scroll-y="true" :scroll-top="scrollTop"  @scroll="scroll">
				<view class="texts">
					<view class="symbles">
						<view style="font-style: 20rpx;font-weight: bolder;color: #333;height: 45rpx;line-height: 100%;margin-bottom: 10rpx;">你好，我是图小言，是一个智能助手</view>
						<br />
						<view style="font-size14px;color: #999;margin-bottom: 20rpx;">作为你的智能伙伴，我既能写文案，想点子又能写代码，做表格</view>
						<br />
						<view style="display: flex;flex-wrap: nowrap;justify-content: space-between;margin-bottom: 20rpx;padding: 5rpx;">
							<view style="font-size14px;color: #999;">你可以试着问我</view>
							<view style="font-size14px;color: #999;display: flex;align-items: center;" class="change" @click="sortAgain">
								<image src="../../static/reload.png" mode="aspectFill" style="width: 32rpx;height: 32rpx;" />换一个
							</view>
						</view>
						<view style="display: flex;flex-wrap: wrap;justify-content: space-between;font-size14px;">
							<view class="symble-item" v-for="(item,index) in simpleList" :key="index" v-if="dateDone" @click="askContent(item.desc)">
								<view style="width: 40rpx;height: 40rpx;">
									<image style="width: 100%;height: 100%;" :src="item.icon" mode="aspectFill" />
								</view>
								<view class="s-title">{{item.title}}</view>
								<view class="s-desc">{{item.desc}}</view>
							</view>
						</view>
					</view>
				</view>
				<view class="texthistory" v-for="(item,index) in answer" :key="index">
					<view class="txtitle" style="" @click="toggleShow(item)">
						<view>{{item.title}}</view>
						<view style="width: 20rpx;height: 20rpx;display: flex;" :class="item.active?'active':''">
							<image src="../../static/down.png" mode="aspectFill"
							style="width: 100%;height: 100%;" />
						</view>
						
					</view>
					<view v-if="item.active" style="padding: 20rpx;">
						<rich-text :nodes="item.contex"></rich-text>
					</view>
					
				</view>
				<view class="currenttext" style="color: #333;padding: 20rpx;">
					{{currentAnswer}}
				</view>
			</scroll-view>
			<up-modal :show="show" :title="'提示'" :content='contetmodal' @confirm="confirm" @cancel="show = false" show-cancel-button="true"></up-modal>
		<view class="uni-input">
			<input placeholder="" v-model="content" class="inputs" style="padding: 0 20rpx;"  />
			<!-- <input placeholder="" v-model="content" class="inputs" style="padding: 0 20rpx;" :adjust-position="false" /> -->
			<image src="../../static/send.png" mode="aspectFill" style="width: 40rpx;height: 40rpx;" @click="askn" />
		</view>
	</view>
</template>

<script setup>
	import { computed, nextTick, onMounted, onUnmounted, reactive } from 'vue';
	import {wxLogin,backLogin,hello} from '../../utis/api.js'
	import {ref} from 'vue'
import { setToken } from '../../utis/authon.js';
	let src = ref("aaaa")
	let websoket = ref();
	const wsUri = ref("ws://47.120.49.37:8080/ws/test")
	let content = ref("")
	let answer = reactive([]);
	let currentAnswer = ref('');
	let dateDone = ref(false);
	let animationDate = ref({});
	let scrollTop = ref(0);
	let old = ref({ scrollTop: 0 }) 
	let contetmodal = ref("当前功能需要用户登录，点击确定注册或登录");
	let simples = reactive([
		{icon:`../../static/1.png`,title:"评析申论范文",desc:"评阅9篇申论范文的优缺点。"},
		{icon:`../../static/2.png`,title:"2024电动汽车年中大盘点",desc:"帮我整理一下2024年电动汽车行业的发展和未来走向"},
		{icon:`../../static/3.png`,title:"南京热门景点",desc:"我来云南旅游，请给我一些热门景"},
		{icon:`../../static/4.png`,title:"活动方案策划",desc:"设计一份党纪学习教育实践活动的方案策划"},
		{icon:`../../static/5.png`,title:"周报日报",desc:"帮我根据以下工作生成一份周报"},
		{icon:`../../static/8.png`,title:"代码编写",desc:"用python设计从0-12随机4个整数"},
		{icon:`../../static/6.png`,title:"小红书文案",desc:"生成一份小红书文案"},
		{icon:`../../static/7.png`,title:"活动方案策划",desc:"设计一份党纪学习教育实践活动的"},
		{icon:`../../static/9.png`,title:"活动方案策划",desc:"设计一份党纪学习教育实践活动的"},
		{icon:`../../static/10.png`,title:"活动方案策划",desc:"设计一份党纪学习教育实践活动的"},
		{icon:`../../static/11.png`,title:"活动方案策划",desc:"设计一份党纪学习教育实践活动的"}
	])
	let okOperate = ref(true);
	let show = ref(false)
	onMounted(()=>{
		sortAgain();
		startws();
		// hello().then(res=>{
		// 	console.log(res)
		// 	uni.showToast({
		// 		title:res.data.data
		// 	})
		// 	startws();
		// })
	})
	onUnmounted(()=>{
		websoket.value.close();
	})
	let simpleList = ref([])
	const clogin = ()=>{
		login();
	}
	
	
	const confirm = ()=>{
		wxLogin().then(res=>{
			if(res.errMsg === "login:ok") {
				backLogin({code:res.code}).then(authon=>{
					if(authon.code === 0) {
						setToken(authon.data.token);
						uni.setStorageSync("session_key",authon.data.session_key);
						uni.setStorageSync("openid",authon.data.openid);
						uni.setStorageSync("token",authon.data.token);
						uni.setStorageSync("nickName",authon.data.nickName);
						uni.setStorageSync("avatarUrl",authon.data.avatarUrl);
						uni.navigateBack({
							delta: 1
						  })
						uni.navigateTo({
						  url: 'pages/views/text',
						})
					}
				})
			} else {
				uni.showToast({
					title:"微信登录失败"
				})
			}
		})
	}
	const startws = ()=>{
		websoket.value = uni.connectSocket({url:wsUri.value,success() {
			console.log("创建成功")
		},fail() {
			console.log("连接失败")
		},complete() {
			console.log("连接完成")
		}});
		websoket.value.onOpen((res)=>{
			console.log(res)
		})
		
		websoket.value.onMessage((res) => {
			okOperate.value = false;
			if(res.data === "current_done") {
				scrollTop.value = old.value.scrollTop;
				okOperate.value = true;
				nextTick(()=>{
					scrollTop.value = 99999;
					answer[answer.length-1].contex = currentAnswer.value;
					currentAnswer.value = "";
				})
			} else {
				let str = res.data.substr(8);
				let data = JSON.parse(str);
				const msg = data.choices[0].delta.content
				currentAnswer.value+=data.choices[0].delta.content;
				toBottom();
			}
		});
	}
	
	const toBottom = async() =>{
		scrollTop.value = old.value.scrollTop 
		await nextTick();
		scrollTop.value = 9999;
	}
	
	const scroll = (e)=>{
		old.value.scrollTop = e.detail.scrollTop
	}

	const generateUniqueNumbers=(count)=> {
	  const uniqueNumbers = new Set();
	  while (uniqueNumbers.size < count) {
	    const randomNumber = Math.floor(Math.random() * 10) + 1;
	    uniqueNumbers.add(randomNumber);
	  }
	  return Array.from(uniqueNumbers);
	}
	 
	const sortAgain = ()=>{
		const numbers = generateUniqueNumbers(4);
		simpleList.value = JSON.parse(JSON.stringify([simples[numbers[0]],simples[numbers[1]],simples[numbers[2]],simples[numbers[3]]]))
		dateDone.value = true;
		let animat = uni.createAnimation({duration:1500,transformOrigin:"50% 50%"}).rotate(90).step();
		//导出动画
		animationDate.value = animat.export()
	}
	
	const askn = ()=>{
		if(!uni.getStorageSync("token")){
			show.value = true
			return;
		} 
		if(content.value){
			answer.push({
				id:answer.length+1,
				title:content.value,
				contex:"",
				active:true
			});
			websoket.value.send({data:content.value+"///token"+uni.getStorageSync("token")});
			nextTick(()=>{
				content.value = "";
			})
			
		}else {
			uni.showToast({
				title:"请输入内容"
			})
		}
		
	}
	
	const askContent=(val)=>{
		content.value = val;
	}
	
	const toggleShow = (item)=>{
		if(okOperate){
			answer.map(el=>{
				if(el.id === item.id){
					el.active = !el.active;
				}
				return el;
			})
		}
		
	}
</script>
<style lang="less">
	::v-deep ::-webkit-scrollbar {
		display: none;
		width: 0;
		height: 0;
		color: transparent;
	}
	.container {
		font-family: system-ui;
		background-color: rgb(245, 242, 245);
		box-sizing: border-box;
		padding: 1vh 1vw;
		padding-top: 2vh;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
		.box{
			box-sizing: border-box;
			max-height: 90vh;
			width: 100%;
			padding: 20rpx;
			border-radius: 20rpx;
			background-color: rgb(254, 254, 254);
			overflow: scroll;
			.texts {
				
				.symble-item{
					box-sizing: border-box;
					padding: 10rpx;
					width: 48%;
					background: rgb(249, 248, 255);
					border-radius: 10rpx;
					margin-bottom: 20rpx;
					height: 20vh;
					.s-title {
						font-weight: bolder;
						margin: 5rpx;
					}
					.s-desc {
						color: #999;
						display: -webkit-box;
						  -webkit-box-orient: vertical;
						  -webkit-line-clamp: 2;
						  overflow: hidden;
						  text-overflow: ellipsis;
					}
				}
			}
			.texthistory{
				background-color: #f9f8ff;border-radius: 10rpx;
				.txtitle{
					color: #999;padding: 20rpx;font-weight: bolder;height: 50rpx;display: flex;flex-wrap: nowrap;align-items: center;justify-content: space-between;
					.active{
						transform: rotate(180deg);
					}
				}
			}
		}
		.textshow{
			width: 100vw;
		}
		.uni-input{
			position: fixed;
			height: 5vh;
			bottom: 1vh;
			width: 100%;
			display: flex;
			flex-wrap: nowrap;
			align-items: center;
			padding: 0 20rpx;
			box-sizing: border-box;
		}
		.inputs {
			width: 85vw;
			background-color: #fff;
			border-radius: 10rpx;
			height: 5vh;
			margin-right: 32rpx;
		}
	}
	
</style>
